October 23, 2021
이 문제는 프로그래머스에서 힙 자료구조를 사용하는 예시 문제로 나와 있는데… 솔직히 왜 힙을 써야하는지 잘 모르겠다. 힙을 안쓰고 리스트로만 구현해도 잘만 풀린다. 혹시 왜 힙 예제인지 이해 가시는 분은 댓글 부탁…
✅ 힙 사용한 풀이
import heapq
def solution(operations):
heap = []
for op in operations:
cmd, n = op.split(" ")
if cmd == "I":
heapq.heappush(heap, int(n))
if len(heap) > 0:
if cmd == "D" and n == "1":
heap.pop(heap.index(heapq.nlargest(1, heap)[0]))
elif cmd == "D" and n == "-1":
heapq.heappop(heap)
if len(heap) == 0:
return [0,0]
else:
return heapq.nlargest(1,heap) + heapq.nsmallest(1, heap)
✅ 그냥 리스트 사용한 풀이
def solution(operations):
result = []
for op in operations:
cmd, n = op.split(" ")
if cmd == "I":
result.append(int(n))
if len(result) > 0:
if cmd == "D" and n == "1":
result.remove(max(result))
elif cmd == "D" and n == "-1":
result.remove(min(result))
if len(result) == 0:
return [0,0]
else:
return [max(result), min(result)]